/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ws.service;

import entidade.persistencia.Usuario;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.QueryParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import com.sun.jersey.api.core.ResourceContext;
import javax.ws.rs.WebApplicationException;
import javax.persistence.NoResultException;
import javax.persistence.EntityManager;
import entidade.persistencia.TipoUsuario;
import entidade.persistencia.Funcionario;
import entidade.persistencia.Manutencao;
import entidade.persistencia.Empresa;
import entidade.persistencia.Venda;
import java.util.List;
import entidade.persistencia.Compra;
import java.util.List;
import ws.converter.UsuarioConverter;

/**
 *
 * @author victorinox
 */

public class UsuarioResource {
    @Context
    protected UriInfo uriInfo;
    @Context
    protected ResourceContext resourceContext;
    protected Integer id;
  
    /** Creates a new instance of UsuarioResource */
    public UsuarioResource() {
    }

    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * Get method for retrieving an instance of Usuario identified by id in XML format.
     *
     * @param id identifier for the entity
     * @return an instance of UsuarioConverter
     */
    @GET
    @Produces({"application/xml", "application/json"})
    public UsuarioConverter get(@QueryParam("expandLevel")
    @DefaultValue("1")
    int expandLevel) {
        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            return new UsuarioConverter(getEntity(), uriInfo.getAbsolutePath(), expandLevel);
        } finally {
            PersistenceService.getInstance().close();
        }
    }

    /**
     * Put method for updating an instance of Usuario identified by id using XML as the input format.
     *
     * @param id identifier for the entity
     * @param data an UsuarioConverter entity that is deserialized from a XML stream
     */
    @PUT
    @Consumes({"application/xml", "application/json"})
    public void put(UsuarioConverter data) {
        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            EntityManager em = persistenceSvc.getEntityManager();
            updateEntity(getEntity(), data.resolveEntity(em));
            persistenceSvc.commitTx();
        } finally {
            persistenceSvc.close();
        }
    }

    /**
     * Delete method for deleting an instance of Usuario identified by id.
     *
     * @param id identifier for the entity
     */
    @DELETE
    public void delete() {
        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            deleteEntity(getEntity());
            persistenceSvc.commitTx();
        } finally {
            persistenceSvc.close();
        }
    }

    /**
     * Returns an instance of Usuario identified by id.
     *
     * @param id identifier for the entity
     * @return an instance of Usuario
     */
    protected Usuario getEntity() {
        EntityManager em = PersistenceService.getInstance().getEntityManager();
        try {
            return (Usuario) em.createQuery("SELECT e FROM Usuario e where e.usuarioId = :usuarioId").setParameter("usuarioId", id).getSingleResult();
        } catch (NoResultException ex) {
            throw new WebApplicationException(new Throwable("Resource for " + uriInfo.getAbsolutePath() + " does not exist."), 404);
        }
    }

    /**
     * Updates entity using data from newEntity.
     *
     * @param entity the entity to update
     * @param newEntity the entity containing the new data
     * @return the updated entity
     */
    protected Usuario updateEntity(Usuario entity, Usuario newEntity) {
        EntityManager em = PersistenceService.getInstance().getEntityManager();
        List<Manutencao> manutencaoCollection = entity.getManutencaoCollection();
        List<Manutencao> manutencaoCollectionNew = newEntity.getManutencaoCollection();
        List<Compra> compraCollection = entity.getCompraCollection();
        List<Compra> compraCollectionNew = newEntity.getCompraCollection();
        Empresa empresaId = entity.getEmpresaId();
        Empresa empresaIdNew = newEntity.getEmpresaId();
        TipoUsuario tipoUsuarioId = entity.getTipoUsuarioId();
        TipoUsuario tipoUsuarioIdNew = newEntity.getTipoUsuarioId();
        List<Funcionario> funcionarioCollection = entity.getFuncionarioCollection();
        List<Funcionario> funcionarioCollectionNew = newEntity.getFuncionarioCollection();
        List<Venda> vendaCollection = entity.getVendaCollection();
        List<Venda> vendaCollectionNew = newEntity.getVendaCollection();
        List<Venda> vendaCollection1 = entity.getVendaCollection1();
        List<Venda> vendaCollection1New = newEntity.getVendaCollection1();
        entity = em.merge(newEntity);
        for (Manutencao value : manutencaoCollection) {
            if (!manutencaoCollectionNew.contains(value)) {
                throw new WebApplicationException(new Throwable("Cannot remove items from manutencaoCollection"));
            }
        }
        for (Manutencao value : manutencaoCollectionNew) {
            if (!manutencaoCollection.contains(value)) {
                Usuario oldEntity = value.getClienteId();
                value.setClienteId(entity);
                if (oldEntity != null && !oldEntity.equals(entity)) {
                    oldEntity.getManutencaoCollection().remove(value);
                }
            }
        }
        for (Compra value : compraCollection) {
            if (!compraCollectionNew.contains(value)) {
                throw new WebApplicationException(new Throwable("Cannot remove items from compraCollection"));
            }
        }
        for (Compra value : compraCollectionNew) {
            if (!compraCollection.contains(value)) {
                Usuario oldEntity = value.getVendedorId();
                value.setVendedorId(entity);
                if (oldEntity != null && !oldEntity.equals(entity)) {
                    oldEntity.getCompraCollection().remove(value);
                }
            }
        }
        if (empresaId != null && !empresaId.equals(empresaIdNew)) {
            empresaId.getUsuarioCollection().remove(entity);
        }
        if (empresaIdNew != null && !empresaIdNew.equals(empresaId)) {
            empresaIdNew.getUsuarioCollection().add(entity);
        }
        if (tipoUsuarioId != null && !tipoUsuarioId.equals(tipoUsuarioIdNew)) {
            tipoUsuarioId.getUsuarioCollection().remove(entity);
        }
        if (tipoUsuarioIdNew != null && !tipoUsuarioIdNew.equals(tipoUsuarioId)) {
            tipoUsuarioIdNew.getUsuarioCollection().add(entity);
        }
        for (Funcionario value : funcionarioCollection) {
            if (!funcionarioCollectionNew.contains(value)) {
                throw new WebApplicationException(new Throwable("Cannot remove items from funcionarioCollection"));
            }
        }
        for (Funcionario value : funcionarioCollectionNew) {
            if (!funcionarioCollection.contains(value)) {
                Usuario oldEntity = value.getUsuarioId();
                value.setUsuarioId(entity);
                if (oldEntity != null && !oldEntity.equals(entity)) {
                    oldEntity.getFuncionarioCollection().remove(value);
                }
            }
        }
        for (Venda value : vendaCollection) {
            if (!vendaCollectionNew.contains(value)) {
                throw new WebApplicationException(new Throwable("Cannot remove items from vendaCollection"));
            }
        }
        for (Venda value : vendaCollectionNew) {
            if (!vendaCollection.contains(value)) {
                Usuario oldEntity = value.getClienteId();
                value.setClienteId(entity);
                if (oldEntity != null && !oldEntity.equals(entity)) {
                    oldEntity.getVendaCollection().remove(value);
                }
            }
        }
        for (Venda value : vendaCollection1) {
            if (!vendaCollection1New.contains(value)) {
                throw new WebApplicationException(new Throwable("Cannot remove items from vendaCollection1"));
            }
        }
        for (Venda value : vendaCollection1New) {
            if (!vendaCollection1.contains(value)) {
                Usuario oldEntity = value.getClienteId();
                value.setClienteId(entity);
                if (oldEntity != null && !oldEntity.equals(entity)) {
                    oldEntity.getVendaCollection1().remove(value);
                }
            }
        }
        return entity;
    }

    /**
     * Deletes the entity.
     *
     * @param entity the entity to deletle
     */
    protected void deleteEntity(Usuario entity) {
        EntityManager em = PersistenceService.getInstance().getEntityManager();
        if (!entity.getManutencaoCollection().isEmpty()) {
            throw new WebApplicationException(new Throwable("Cannot delete entity because manutencaoCollection is not empty."));
        }
        if (!entity.getCompraCollection().isEmpty()) {
            throw new WebApplicationException(new Throwable("Cannot delete entity because compraCollection is not empty."));
        }
        Empresa empresaId = entity.getEmpresaId();
        if (empresaId != null) {
            empresaId.getUsuarioCollection().remove(entity);
        }
        TipoUsuario tipoUsuarioId = entity.getTipoUsuarioId();
        if (tipoUsuarioId != null) {
            tipoUsuarioId.getUsuarioCollection().remove(entity);
        }
        if (!entity.getFuncionarioCollection().isEmpty()) {
            throw new WebApplicationException(new Throwable("Cannot delete entity because funcionarioCollection is not empty."));
        }
        if (!entity.getVendaCollection().isEmpty()) {
            throw new WebApplicationException(new Throwable("Cannot delete entity because vendaCollection is not empty."));
        }
        if (!entity.getVendaCollection1().isEmpty()) {
            throw new WebApplicationException(new Throwable("Cannot delete entity because vendaCollection1 is not empty."));
        }
        em.remove(entity);
    }

    /**
     * Returns a dynamic instance of ManutencaoesResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of ManutencaoesResource
     */
    @Path("manutencaoCollection/")
    public ManutencaoesResource getManutencaoCollectionResource() {
        ManutencaoCollectionResourceSub resource = resourceContext.getResource(ManutencaoCollectionResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    /**
     * Returns a dynamic instance of ComprasResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of ComprasResource
     */
    @Path("compraCollection/")
    public ComprasResource getCompraCollectionResource() {
        CompraCollectionResourceSub resource = resourceContext.getResource(CompraCollectionResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    /**
     * Returns a dynamic instance of EmpresaResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of EmpresaResource
     */
    @Path("empresaId/")
    public EmpresaResource getEmpresaIdResource() {
        EmpresaIdResourceSub resource = resourceContext.getResource(EmpresaIdResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    /**
     * Returns a dynamic instance of TipoUsuarioResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of TipoUsuarioResource
     */
    @Path("tipoUsuarioId/")
    public TipoUsuarioResource getTipoUsuarioIdResource() {
        TipoUsuarioIdResourceSub resource = resourceContext.getResource(TipoUsuarioIdResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    /**
     * Returns a dynamic instance of FuncionarioesResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of FuncionarioesResource
     */
    @Path("funcionarioCollection/")
    public FuncionarioesResource getFuncionarioCollectionResource() {
        FuncionarioCollectionResourceSub resource = resourceContext.getResource(FuncionarioCollectionResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    /**
     * Returns a dynamic instance of VendasResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of VendasResource
     */
    @Path("vendaCollection/")
    public VendasResource getVendaCollectionResource() {
        VendaCollectionResourceSub resource = resourceContext.getResource(VendaCollectionResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    /**
     * Returns a dynamic instance of VendasResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of VendasResource
     */
    @Path("vendaCollection1/")
    public VendasResource getVendaCollection1Resource() {
        VendaCollection1ResourceSub resource = resourceContext.getResource(VendaCollection1ResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    public static class ManutencaoCollectionResourceSub extends ManutencaoesResource {

        private Usuario parent;

        public void setParent(Usuario parent) {
            this.parent = parent;
        }

        @Override
        protected List<Manutencao> getEntities(int start, int max, String query) {
            List<Manutencao> result = new java.util.ArrayList<Manutencao>();
            int index = 0;
            for (Manutencao e : parent.getManutencaoCollection()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }

    public static class CompraCollectionResourceSub extends ComprasResource {

        private Usuario parent;

        public void setParent(Usuario parent) {
            this.parent = parent;
        }

        @Override
        protected List<Compra> getEntities(int start, int max, String query) {
            List<Compra> result = new java.util.ArrayList<Compra>();
            int index = 0;
            for (Compra e : parent.getCompraCollection()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }

    public static class EmpresaIdResourceSub extends EmpresaResource {

        private Usuario parent;

        public void setParent(Usuario parent) {
            this.parent = parent;
        }

        @Override
        protected Empresa getEntity() {
            Empresa entity = parent.getEmpresaId();
            if (entity == null) {
                throw new WebApplicationException(new Throwable("Resource for " + uriInfo.getAbsolutePath() + " does not exist."), 404);
            }
            return entity;
        }
    }

    public static class TipoUsuarioIdResourceSub extends TipoUsuarioResource {

        private Usuario parent;

        public void setParent(Usuario parent) {
            this.parent = parent;
        }

        @Override
        protected TipoUsuario getEntity() {
            TipoUsuario entity = parent.getTipoUsuarioId();
            if (entity == null) {
                throw new WebApplicationException(new Throwable("Resource for " + uriInfo.getAbsolutePath() + " does not exist."), 404);
            }
            return entity;
        }
    }

    public static class FuncionarioCollectionResourceSub extends FuncionarioesResource {

        private Usuario parent;

        public void setParent(Usuario parent) {
            this.parent = parent;
        }

        @Override
        protected List<Funcionario> getEntities(int start, int max, String query) {
            List<Funcionario> result = new java.util.ArrayList<Funcionario>();
            int index = 0;
            for (Funcionario e : parent.getFuncionarioCollection()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }

    public static class VendaCollectionResourceSub extends VendasResource {

        private Usuario parent;

        public void setParent(Usuario parent) {
            this.parent = parent;
        }

        @Override
        protected List<Venda> getEntities(int start, int max, String query) {
            List<Venda> result = new java.util.ArrayList<Venda>();
            int index = 0;
            for (Venda e : parent.getVendaCollection()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }

    public static class VendaCollection1ResourceSub extends VendasResource {

        private Usuario parent;

        public void setParent(Usuario parent) {
            this.parent = parent;
        }

        @Override
        protected List<Venda> getEntities(int start, int max, String query) {
            List<Venda> result = new java.util.ArrayList<Venda>();
            int index = 0;
            for (Venda e : parent.getVendaCollection1()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }
}
